import { setToken, getToken, removeToken } from "@/utils/token"
import { getUserProfile, logout, getLoginStatus } from '@/api'
const state = {
    token: getToken(),
    profile: {
        profile: {
            nickname: '',
            avatarUrl: ''
        }
    },
    timer: null
}

const actions = {

    // 获取用户信息
    async userProfile(context, val) {
        let data = await getUserProfile(val);
        console.log("用户信息", data);
        if (data.code == 200) {
            context.commit('USERPROFILE', data);
        }
    },

    // 获取用户登录状态
    async userStatus(context, val) {
        let data = await getLoginStatus();
        if (!data.data.profile) {
            uni.showToast({
                title: '您尚未登录,请先登录',
                duration: 2000
            });
            context.state.timer
                = setTimeout(() => {
                    uni.redirectTo({
                        url: "/pages/login/index"
                    });
                    clearTimeout(context.state.timer);
                    context.state.timer = null;
                }, 2000)
        }
    },

    // 用户退出登录
    async userLogout(context, val) {
        let data = await logout();
        if (data.code == 200) {
            context.commit('USERLOGOUT');
        }
        console.log(data);
    }
}

const mutations = {
    USERPROFILE(state, val) {
        state.profile = val || {}
    },

    USERLOGOUT(state, val) {
        // 清空token和cookie以及用户记录
        removeToken();
        state.token = '';
        state.profile = {
            profile: {}
        }
        // 跳转登录页
        uni.navigateTo({
            url: '/pages/login/index'
        });
    }
}


export default {
    namespaced: true,
    mutations,
    actions,
    state
}


